
import redis.clients.jedis.Jedis;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import java.util.List;
import java.util.Map;

public class CMapDbl {
	private int maxlen = 5;
	private Jedis maps;
	private String mainkey = "BT";

	public CMapDbl() {
		// 连接redis服务器(在这里是连接本地的)
		maps = RedisPool.getJedis();
		// 权限认证
		// maps.auth("chenhaoxiang");
		// System.out.println("连接服务成功");
	}

	public static List<Double> sortByValue(List<Double> set,boolean flag) {

		Collections.sort(set, new Comparator<Double>() {
			@Override
			public int compare(Double o1, Double o2) {
				// TODO Auto-generated method stub
				if (flag)
					return o1.compareTo(o2);	
				else
					return o2.compareTo(o1);
			}
		});
		return set;
	}

	public long getLen() {
		return maps.hlen(mainkey);
	}

	public synchronized void remove(Double field, Double value) {
		String fi = field.toString();
		if (maps.hexists(mainkey, fi)) {
			Double v = Double.valueOf(maps.hget(mainkey, fi));
			if (v.compareTo(value) > 0) {
				v = v - value;
				maps.hset(mainkey, fi, v.toString());
			} else {
				maps.hdel(mainkey, fi);
			}
		}
	}

	public synchronized void add(Double field, Double value) {
		String fi = field.toString();
		if (maps.hexists(mainkey, fi)) {
			Double v = Double.valueOf(maps.hget(mainkey, fi));
			v = v + value;
			maps.hset(mainkey, fi, v.toString());
		} else {
			maps.hset(mainkey, fi, value.toString());
		}

	}

	public void foreach(Itestfun itf) {

		Map<String, String> s0 = maps.hgetAll(mainkey);
		ArrayList<Double> t = new ArrayList<Double>();
		for (String s : s0.keySet()) {
			t.add(Double.valueOf(s));
		}

		List<Double> set1 = sortByValue(t,true);
		int i = 0;
		for (Double a : set1) {
			// System.out.prDoubleln("ccc"+a);
			if (i++ >= maxlen)
				break;

			System.out.println(a + ", " + s0.get(a.toString()));

		}
		System.out.println("--------------------");
	}

	public List<String> getList(boolean flag) {

		Map<String, String> s0 = maps.hgetAll(mainkey);
		ArrayList<Double> t = new ArrayList<Double>();
		for (String s : s0.keySet()) {
			t.add(Double.valueOf(s));
		}
		List<Double> set1 = sortByValue(t,flag);
		List<String> l2 = new ArrayList<String>();
		int i = 0;
		for (Double a : set1) {
			// System.out.prDoubleln("ccc"+a);
			if (i++ >= maxlen)
				break;
			l2.add(a + "," + s0.get(a.toString()));
		}
		return l2;

	}

}
